In JavaScript, there are two types of comparison operators: strict and non-strict.
- Strict operators: These operators compare both value and type. They are represented as
===
(strict equality) and !==
(strict inequality). For example, 5 === "5"
would return false
because, although the values are the same, the types are
different (one is a number, the other is a string).
- Non-Strict operators: These operators compare only value, not type. They are represented as
==
(equality) and !=
(inequality). For example, 5 == "5"
would return true
because the values are the same, even though the types are
different.
It’s generally recommended to use strict operators in JavaScript to avoid unexpected results due to JavaScript’s type coercion. This is because
non-strict operators can lead to some counter-intuitive results. For example, 0 == false
would return true
, which might not
be the expected outcome.
function checkEqual(a, b) {
if (a == b) { // Noncompliant: using non-strict equality '=='
return "Equal";
} else {
return "Not equal";
}
}
console.log(checkEqual(0, false)); // Output: "Equal"
You should use the strict equality and inequality operators to prevent type coercion, avoid unexpected outcomes when comparing values of different
types, and provide more predictable results.
function checkEqual(a, b) {
if (a === b) {
return "Equal";
} else {
return "Not equal";
}
}
console.log(checkEqual(0, false)); // Output: "Not equal
Exceptions
The rule does not report on these cases:
- Comparing two literal values
- Evaluating the value of
typeof
- Comparing against
null